package com.ruoyi.web.controller.system;

import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Api("系统用户")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Value("${server.port}")
    private String port;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 登录方法
     *
     * @param data 登录信息
     * @return 结果
     */
    @PostMapping("/loginEncodData")
    @ApiOperation("登录")
    @Anonymous
    public AjaxResult loginEncodData(@RequestBody Map<String,String> data)
    {
        String key = "secret";
        String decrypt = decrypt(data.get("data"), key);
        LoginBody loginBody = JSONUtil.toBean(decrypt, LoginBody.class);

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        LoginUser loginUser = loginService.login1(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        String url = "http://127.0.0.1:"+port+"/combat/phone/editStatus?";

        String phonenumber = loginUser.getUser().getPhonenumber();
        if(StringUtils.isNotEmpty(phonenumber)){
            url = url + "phoneNum=" + phonenumber+"&status=1";
            HttpUtil.get(url);
        }
        ajax.put("phoneNumber", phonenumber);
        return ajax;
    }

    public String decrypt(String encryptedText, String password) {
        StringBuilder result = new StringBuilder();

        // 每两个字符代表一个16进制字节
        for (int i = 0; i < encryptedText.length(); i += 2) {
            // 解析16进制字符串
            String hex = encryptedText.substring(i, i + 2);
            int charCode = Integer.parseInt(hex, 16);

            // 与密码字符异或（反向操作）
            int pwdChar = password.charAt((i/2) % password.length());
            charCode = charCode ^ pwdChar;

            // ASCII码反向位移（-5）
            charCode -= 5;

            result.append((char) charCode);
        }

        return result.toString();
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("获取用户信息")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
